<?php

namespace app\controllers\admin\uni\product;

use app\controllers\admin\base\AdminController;
use app\models\product\ProductCategory as Model;
use app\util\Tree;
use yii\helpers\ArrayHelper;
use app\controllers\admin\services\Category as Service;

class CategoryController extends AdminController
{
    public function actionTree()
    {
        $list = Model::find()
            ->where(['status' => Model::$statusMapping['OK']])
            ->orderBy(['id' => SORT_ASC])
            ->asArray()
            ->all();
        $list = Tree::create($list, 'id', 'parent_id', 'children', 0);

        return $this->success($list);
    }

    public function actionList()
    {
        $name = $this->post('name');
        $id = $this->post('id');
        $status = $this->post('status');
        $parent_id = intval($this->post('parent_id'));
        $export = $this->post('export');

        $page = intval($this->post('page', $this->page));
        $page_size = intval($this->post('pageSize', $this->pageSize));

        $sort = $this->post('sort');

        $query = Model::find()
            ->where(['!=', 'status', Model::$statusMapping['DELETE']])
            ->with(['image', 'parent']);

        if ($status > Model::$statusMapping['ALL']) {
            $query->andWhere(['status' => $status]);
        }

        if ($sort) {
            $prop = substr($sort, 0, 1);
            $prop = $prop == '-' ? SORT_DESC : SORT_ASC;
            $order = substr($sort, 1);
            $query->orderBy([$order => $prop]);
        } else {
            $query->orderBy(['sort' => SORT_ASC, 'id' => SORT_DESC]);
        }

        if ($id) {
            $query->andWhere(['id' => $id]);
        }
        if ($name) {
            $query->andWhere(['like', 'name', $name]);
        }
        if ($parent_id > 0) {
            $query->andWhere(['parent_id' => $parent_id]);
            // 所有子类(多层次)
            // $children = Model::getCategoriesByParent($parent_id, true);
            // $children = ArrayHelper::getColumn($children, 'id');
            // $query->andWhere(['parent_id' => $children]);
        }

        // export
        if ($export) {
            return $this->success($query->asArray()->all());
        }

        $totalCount = $query->count();
        $totalPage = ceil($totalCount / $page_size);

        $list = $query->offset(($page - 1) * $page_size)
            ->limit($page_size)
            ->asArray()
            ->all();

        return $this->success([
            $this->totalCount   => $totalCount,
            $this->totalPage    => $totalPage,
            $this->list         => $list,
        ]);

    }

    public function actionEdit()
    {
        $data = $this->post();

        try {
            if (isset($data['id']) && $data['id'] > 0) {

                // 处理编辑时的死循环
                if ($data['parent_id'] > 0 && $data['id'] == $data['parent_id']) {
                    throw new \Exception('分类选择错误: 不能成为自己的子分类1');
                }

                // 获取全部子分类
                $children = Model::getCategoriesByParent($data['id'], true);
                $children = ArrayHelper::getColumn($children, 'id');
                if (in_array($data['parent_id'], $children)) {
                    throw new \Exception('分类选择错误: 不能成为自己子分类的子分类2');
                }

                $model = Model::findOne(['id' => $data['id']]);
                if (!$model) {
                    return $this->fail('操作失败');
                }
            } else {
                $model = new Model();
            }
            $data = ['ProductCategory' => $data];
            if ($model->load($data) && $model->save()) {
                return $this->success($model, '操作成功');
            }
        } catch (\Exception $e) {
            return $this->fail($e->getMessage());
        }
    }

    public function actionView()
    {
        $id = $this->post('id');
        $model = Model::find()
            ->where(['id' => $id])
            ->with(['image'])
            ->asArray()
            ->one();

        if ($model) {
            return $this->success($model);
        }

        return $this->fail('不存在该分类');
    }

    public function actionRemove()
    {
        $id = $this->post('id');

        $children = Model::getCategoriesByParent($id, true);
        if (!empty($children)) {
            return $this->fail('存在子分类, 不能删除');
        }

        // todo exist product

        try {
            $model = Model::findOne(['id' => $id]);
            $model->status = Model::$statusMapping['DELETE'];
            $model->save();
            return $this->success($model, '删除成功');
        } catch (\Exception $e) {
            return $this->fail($e->getMessage());
        }
    }

    public function actionStatusList()
    {
        return $this->success(Model::statusList());
    }

    public function actionChangeStatus()
    {
        $id = intval($this->post('id'));
        $status = intval($this->post('status'));

        try {
            $model = Model::findOne(['id' => $id]);
            $model->status = $status;
            $model->save();

            return $this->success();
        } catch (\Exception $e) {
            return $this->fail('操作错误: ' . $e->getMessage());
        }
    }

    public function actionChangeSort()
    {
        $id = intval($this->post('id'));
        $sort = intval($this->post('sort'));

        try {
            $model = Model::findOne(['id' => $id]);
            $model->sort = $sort;
            $model->save();

            return $this->success();
        } catch (\Exception $e) {
            return $this->fail('操作错误: ' . $e->getMessage());
        }
    }

    public function actionBatchRemove()
    {
        $ids = $this->post('ids');

        try {
            // todo exist children category or product

            Model::updateAll(['status' => Model::$statusMapping['DELETE']], ['id' => $ids]);

            return $this->success();
        } catch (\Exception $e) {
            return $this->fail('删除错误: ' . $e->getMessage());
        }
    }
}